package system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import common.config.exception.CustomException;
import common.model.enums.EmailNotifyTypeEnum;
import common.model.enums.SysTopicIsClosedEnum;
import common.model.po.SysTopic;
import common.model.po.SysTopicComment;
import common.model.po.SysUser;
import common.model.request.SendEmailRequest;
import common.model.request.base.PaginationRequest;
import common.model.response.base.Result;
import common.util.EmailTemplateUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import system.mapper.SysTopicCommentMapper;
import system.model.converter.SysTopicCommentConverter;
import system.model.request.ModifyTopicCommentSortRequest;
import system.model.request.SaveTopicCommentRequest;
import system.model.request.SearchTopicCommentRequest;
import system.model.vo.SysTopicCommentVo;
import system.service.MailService;
import system.service.SysTopicCommentService;
import system.service.SysTopicService;
import system.service.SysUserService;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * 服务实现类
 *
 * @author 米泽鹏
 * @since 2023-09-12 下午 09:46
 */
@Service
public class SysTopicCommentServiceImpl extends ServiceImpl<SysTopicCommentMapper, SysTopicComment> implements SysTopicCommentService {

	@Resource
	private SysTopicCommentMapper mapper;
	@Resource
	private SysTopicService topicService;
	@Resource
	private MailService mailService;
	@Resource
	private SysUserService userService;
	@Value("${satisfactory.domain}")
	private String domain;

	@Override
	public Page<SysTopicCommentVo> pageTopicComment(PaginationRequest<SearchTopicCommentRequest, SysTopicComment> paginationRequest) {
		return mapper.pageSysTopicComment(paginationRequest.buildPage(), paginationRequest.getParams());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> saveTopicComment(SaveTopicCommentRequest request) {
		// 校验要评论的话题是否存在
		SysTopic topic = topicService.getById(request.getTopicId());
		if (topic == null) {
			throw new CustomException("网页数据已过期，请刷新页面后重试（话题不存在）");
		}
		// 校验要评论的话题是否已被关闭
		if (SysTopicIsClosedEnum.CLOSED.getValue().equals(topic.getIsClosed())) {
			throw new CustomException("该话题已关闭，无法评论");
		}
		// 校验要评论的父级评论是否存在
		if (!request.getParentId().equals(0L) && getById(request.getParentId()) == null) {
			throw new CustomException("网页数据已过期，请刷新页面后重试（评论不存在）");
		}
		SysTopicComment messageReply = SysTopicCommentConverter.saveRequestToPo(request);
		if (messageReply.getId() == null) {
			save(messageReply);
			// 邮件通知被回复的用户
			SysUser replyToUser = userService.getById(messageReply.getReplyToUserId());
			if (!replyToUser.getId().equals(messageReply.getUserId()) && EmailNotifyTypeEnum.check(EmailNotifyTypeEnum.COMMENT_ON_ME, replyToUser)) {
				SendEmailRequest sendEmailRequest = new SendEmailRequest();
				sendEmailRequest.setToList(Collections.singletonList(replyToUser.getEmail()));
				sendEmailRequest.setSubject(EmailNotifyTypeEnum.COMMENT_ON_ME.getDesc() + "【幸福工厂游戏工具网站】");
				sendEmailRequest.setText(EmailTemplateUtil.getCommentOnMeContent(domain, messageReply.getContent(), messageReply.getNickname()));
				sendEmailRequest.setHtml(true);
				mailService.sendEmail(sendEmailRequest);
			}
		} else {
			updateById(messageReply);
		}
		return Result.success();
	}

	@Override
	public Result<?> deleteTopicComment(Long id) {
		removeById(id);
		return Result.success();
	}

	@Override
	public Result<?> modifyTopicCommentSort(ModifyTopicCommentSortRequest request) {
		lambdaUpdate().eq(SysTopicComment::getId, request.getTopicCommentId()).set(SysTopicComment::getSort, request.getSort()).update();
		return Result.success();
	}

}
